-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
35 lines (30 loc) · 1.12 KB
/
Solution.java
File metadata and controls
35 lines (30 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Scanner;
import java.util.Stack;
public class PostfixEvaluator {
public static int evaluatePostfix(String expression) {
Stack<Integer> stack = new Stack<>();
for (char ch : expression.toCharArray()) {
if (Character.isDigit(ch)) {
stack.push(ch - '0');
} else {
int val2 = stack.pop();
int val1 = stack.pop();
switch (ch) {
case '+': stack.push(val1 + val2); break;
case '-': stack.push(val1 - val2); break;
case '*': stack.push(val1 * val2); break;
case '/': stack.push(val1 / val2); break;
case '^': stack.push((int)Math.pow(val1, val2)); break;
}
}
}
return stack.pop();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter postfix expression: ");
String expression = sc.next();
int result = evaluatePostfix(expression);
System.out.println("Result: " + result);
}
}